package com.demo.mvc.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author luogq
 * @date  2021.1.4
 * 线程池配置
 */
@Configuration
@EnableAsync
public class TaskExecutePool {

    @Value("${async.executor.thread.core_pool_size:10}")
    private int corePoolSize;
    @Value("${async.executor.thread.max_pool_size:60}")
    private int maxPoolSize;
    @Value("${async.executor.thread.queue_capacity:500}")
    private int queueCapacity;
    @Value("${async.executor.thread.name.prefix:Async-Exec}")
    private String namePrefix;

    @Bean
    public Executor myTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程池大小
        executor.setCorePoolSize(corePoolSize);
        //最大线程数
        executor.setMaxPoolSize(maxPoolSize);
        //队列容量
        executor.setQueueCapacity(queueCapacity);
        //活跃时间
        executor.setKeepAliveSeconds(10);
        //线程名字前缀
        executor.setThreadNamePrefix(namePrefix);
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}
